package com.xxwy.unionfind;

/**
 * @author xxwy
 */
public class UnionFind32 implements UF {

    private int[] parent;
    //rank[i],表示i根节点的层数
    private int[] rank;

    public UnionFind32(int size) {
        parent = new int[size];
        rank = new int[size];
        for (int i = 0; i < size; i++) {
            parent[i] = i;
            rank[i] = 1;
        }
    }

    @Override
    public int getSize() {
        return parent.length;
    }

    @Override
    public boolean isConnected(int p, int q) {
        return find(p) == find(q);
    }

    /**
     * 查找过程，查找元素p对应的集合编号
     * O(h)复杂度，h为树的高度
     * @param p
     * @return
     */
    private int find(int p){
        if(p <0 || p>=parent.length){
            throw new IllegalArgumentException("p is out of bound");
        }
        while (p != parent[p]){
            p = parent[p];
        }
        return p;
    }

    @Override
    public void unionElements(int p, int q) {
        if(p <0 || p>=parent.length|| q <0 || q >= parent.length){
            throw new IllegalArgumentException("p is out of bound");
        }
        int qRoot = find(q);
        int pRoot = find(p);
        if(pRoot == qRoot){
            return;
        }
        if(rank[pRoot] < rank[qRoot]){
            parent[pRoot] = qRoot;
        }else if(rank[pRoot] >rank[qRoot]){
            parent[qRoot] = pRoot;
        }else {
            parent[qRoot] = pRoot;
            rank[pRoot]+=1;
        }
    }


}
